<?php
$dir = sfConfig::get('sf_symfony_lib_dir');
require_once $dir.DIRECTORY_SEPARATOR.'helper'.DIRECTORY_SEPARATOR.'UrlHelper.php';
require_once $dir.DIRECTORY_SEPARATOR.'helper'.DIRECTORY_SEPARATOR.'TagHelper.php';

class searchActions extends sfActions
{
	public function executeRenderSearchBar(sfWebRequest $request){
		$html = '';
		$className = $request->getParameterHolder()->get('className');
		$fieldName = $request->getParameterHolder()->get('fieldName');
		$form = new filterspecForm;
		$form->setSearchType('quick');
		$form->setFields($className);
		$type = $form->setFilterType($fieldName,$className, '');
		$form['fieldName']->getWidget()->setAttributes(array(
			'class' => 'searchSmallCombobox',
	 		'onchange'=> 'reRenderSearchBar();',
		 ));
		 
		
		return  $this->renderPartial('quickSearchForm', array('form' => $form, 'type'=>$type));
	}
	
	public function executeRenderAdvancedSearch(sfWebRequest $request){
		sfConfig::set('sf_web_debug', false);
		$className = $request->getParameterHolder()->get('className');
		$fieldName = $request->getParameterHolder()->get('fieldName');
		$operator = $request->getParameterHolder()->get('operator');
		$form = new filterspecForm;
		$form->setSearchType('avanced');
		$form->setFields($className);
		$type = $form->setFilterType($fieldName,$className, $operator);
		$form->offsetGet('fieldName')->getWidget()->setAttributes(array(
			'class' => 'searchCombobox',
	 		'onchange'=> 'showAdvancedSearch();',
		 ));
		$form->offsetGet('operator')->getWidget()->setAttributes(array(
			'class' => 'searchCombobox',
	 		'onchange'=> 'showAdvancedSearch();',
		 )); 			
		 $form->setLabels(); 
		return  $this->renderPartial('advancedSearchForm', array('form' => $form));
	}	
	
	public function executeRenderSaveSearch(sfWebRequest $request){
		sfConfig::set('sf_web_debug', false);
		$filter_id = $request->getParameter('filter_id');
		if($filter_id=='new'){
			$form = new filterdefForm();
		}else{
			$filterDef = Doctrine::getTable('filterdef')->find($filter_id);
			$form = new filterdefForm($filterDef);
		}
		
		return  $this->renderPartial('saveSearchForm', array('form' => $form));
	}	
	
	public function executeRenderApplySearch(sfWebRequest $request){
		sfConfig::set('sf_web_debug', false);
		$className = $request->getParameterHolder()->get('className');
		$form = new applySearchForm;
		$form->setSearchDefCandidates($className);
		return  $this->renderPartial('applySearchForm', array('form' => $form));
	}		
	
	public function executeAddFilters(sfWebRequest $request){
		$sf_user= $this->getUser();
		sfConfig::set('sf_web_debug', false);
		//Parametres a ajouter à la fonction js.
		$params = $request->getParameter('refreshParams');
		$formName = $request->getParameter('searchformName');
		$form = new filterspecForm();
		if($formName == 'searchForm'){
			//C'est la recherche rapide
			$name = 'qff';
			$quickSearch = true;
			$closeFunction = '';
		}else{
			//c'est la recherche avancé
			$name = 'aff';
			$quickSearch = false;
			$closeFunction = 'window.top.window.closeAdvancedSearch();';
		}
		$formValues = $request->getParameter($name);
		$search = new searchBar();
	 	$search->createFilter($formValues, $sf_user);
	 	$msg = $this->getFilterMsg($formValues['className']);
	 	if ($sf_user->hasFlash('filterError')){
				$msg .= $sf_user->getFlash('filterError');
		}
			
	 	$html = '<script language="javascript" type="text/javascript">' . $closeFunction . 'window.top.window.refresh('.$params.');window.top.window.showFilterWarning(\''. $msg .'\');</script>';
		return $this->renderText($html);
	}
	
	public function executeApplySearch(sfWebRequest $request){
		$sf_user= $this->getUser();
		sfConfig::set('sf_web_debug', false);
		//Parametres a ajouter � la fonction js.
		$id = $request->getParameter('search');
		$params = $request->getParameter('refreshParams');
		//$filterDef = Doctrine::getTable('filterdef')->find($id);
		
		$q=Doctrine_Query::create()->from('filterspec a'); 
	 	$q->andWhere('a.owner_id = ?',$id);
	 	$result= $q->execute();
	 	$activeFilters = array();
		foreach($result as $filter){
			$activeFilters[$filter->fieldName] = $filter;	
		}
		$sf_user->setAttribute('activeFilters',$activeFilters);
		
	 	$msg = $this->getFilterMsg($formValues['className']);
	 	if ($sf_user->hasFlash('filterError')){
				$msg .= $sf_user->getFlash('filterError');
		}	
	 	$html = '<script language="javascript" type="text/javascript">window.top.window.closeApplySearch();window.top.window.refresh('.$params.');window.top.window.showFilterWarning(\''. $msg .'\');</script>';
		return $this->renderText($html);
	}	
	
	private function getFilterMsg($className = null){
		$i18 = sfContext::getInstance()->getI18N();
		$activeFilters = $this->getUser()->getAttribute('activeFilters');
		$warnings = '';
	 	if(count($activeFilters)>0){
			$warnings = '';
			$filterDef_id = "'new'";
		  	$filterName = '';
		  	foreach($activeFilters as $field => $filterSpec){
		  		if($className == $filterSpec->className or is_null($className)){
		  			if($filterSpec->owner_id){
		  				$filterDef_id = $filterSpec->owner_id; 
		  				$filterName = $filterSpec->owner->description;
		  			}
		 			$warnings .='<p style="text-indent: 10px; margin: 0 padding: 0;">';
			  		//$warnings .='<a href="javascript:clearFilters(\\\''.$field.'\\\')"><img src="/images/icons/16/eliminer.png" title="'. $i18->__('Clear this filtre').'"></img></a>';
			  		$warnings .='<a href="javascript:clearFilters(\''.$field.'\');"><img src="/images/icons/16/filterClear.png" title="'. $i18->__('Clear this filtre').'"></img></a>';
			  		$warnings .= $filterSpec->warningText .'</p>';
		  		}else{
		  			$warnings = '';
		  		}
		  	}
		  	if($warnings != ''){
			  	$prewarnings = '<div style="float: right;">';
			  	if($filterDef_id!="'new'"){
			  		$prewarnings .= '<a href="javascript:deleteSavedSearch('.$filterDef_id.');"><img src="/images/icons/16/filterDelete.png" title="'.$i18->__('Delete this filter from database').'"></img></a>';
			  	}
				$prewarnings .= '<a href="javascript:showSaveForm('.$filterDef_id.');"><img src="/images/icons/16/savefilter.png" title="'.$i18->__('Save current filtres').'"></img></a><nbsp /><a href="javascript:clearFilters(\'\');"><img src="/images/icons/16/resetSearch.png" title="'.$i18->__('Clear all filtres').'"></img></a>';
				$prewarnings .= '</div>';
		 		$prewarnings .='<h3>' . $i18->__('Active Filter :') . ' ' . str_replace("'","\'",$filterName) . '</h3>';
		 		$warnings = $prewarnings . $warnings;
		  	}
	 	}
		return str_replace("'","\'",html_entity_decode(htmlentities($warnings, ENT_QUOTES)));
	}
	
	
	public function executeRemoveFilters(sfWebRequest $request){
		sfConfig::set('sf_web_debug', false);
		$fieldName = $request->getParameterHolder()->get('id');
		$params = $request->getParameter('refreshParams');
		if(isset($fieldName)){
			$activeFilters = $this->getUser()->getAttribute('activeFilters');
			unset($activeFilters[$fieldName]);
			if(count($activeFilters)==0){
				$this->getUser()->getAttributeHolder()->remove('activeFilters');
			}else{
				$this->getUser()->setAttribute('activeFilters',$activeFilters);
			}
		}else{
			$this->getUser()->getAttributeHolder()->remove('activeFilters');
		}
		$sf_user= $this->getUser();
	 	$msg = $this->getFilterMsg();
		if ($sf_user->hasFlash('filterError')){
				$msg .= $sf_user->getFlash('filterError');
		}	
	 	$html = '<script language="javascript" type="text/javascript">window.top.window.showFilterWarning(\''. $msg .'\');window.top.window.refresh('.$params.');</script>';
	 	
		return $this->renderText($html);
		
	}
	
	public function executeSaveFilters(sfWebRequest $request){
		sfConfig::set('sf_web_debug', false);
		$i18 = sfContext::getInstance()->getI18N();
		$form = new filterdefForm();
		$params = $request->getParameter($form->getName());
		if($params['id']){
			$filterDef = Doctrine::getTable('filterdef')->find($params['id']);
			$form = new filterdefForm($filterDef);
		}else{
			$form = new filterdefForm();	
		}
		$form->bind($params); 
		$search = new searchBar();
		$filterDef = $search->saveFilters($form);
		$msg = $this->getFilterMsg();

		$msg .=  str_replace("'","\'",'<p>'.$filterDef->description . ' ' . $i18->__('Saved') . '</p>');
	 	$html = '<script language="javascript" type="text/javascript">window.top.window.closeSaveSearch();window.top.window.showFilterWarning(\''. $msg .'\');</script>';
	 	
		return $this->renderText($html);
		
	}
	public function executeDeleteSavedSearch(sfWebRequest $request){
		sfConfig::set('sf_web_debug', false);
		$id = $request->getParameterHolder()->get('filter_id');
		$filterDef = Doctrine::getTable('filterdef')->find($id);
		$q=Doctrine_Query::create()->from('filterspec a'); 
	 	$q->andWhere('a.owner_id = ?',$id);
	 	$result= $q->execute();
	 	$activeFilters = array();
	 	$conn = Doctrine_Manager::getInstance()->getConnection('doctrine');
	 	$conn->beginTransaction();
		foreach($result as $filter){
			$filter->delete();	
		}
		$filterDef->delete();
		$conn->commit();
		return $this->renderText('');
	}
}